import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { NbTokenService } from '@nebular/auth';

@Injectable()
export abstract class NgxhttpService {

  constructor(private tokenService: NbTokenService, private router : Router) {}

  /**
   * 处理错误信息，将服务端和系统错误消息暴露出来
   * @param error
   * @returns {Observable<never>}
   */
  handleError(error: HttpErrorResponse) {
    //this.cookieExpress(); // todo 暂时这样写的，应该的方式是：和后端约定，在cookie状态为注销时调用这个方法
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    // return an observable with a user-facing error message
    return throwError(
      'Something bad happened; please try again later.');
  };

  private cookieExpress(): void {
    this.tokenService.clear();
    this.router.navigate(['auth/login']);
  };
}
